/**
 * Created by xiewei on 11/5/15.
 * common params and functions
 */
/**
 * 图片加载前的默认图片
  * @type {{master: string, pet: string, photo: string}}
 */
var iconImgs = {
    master: 'icon_master_head@2x.png',
    pet: 'icon_pet_head@2x.png',
    photo: 'photo_select_load@2x.png'
}
/**
 * 服务、环境、评级对应图片
 * @type {{large: string, medium: string, small: string, baby: string, cat: string, pet: string, 55067: string, 57302: string}}
 */
var serveImgMap = {
    large: 'icon_detail_select_large@2x.png',
    medium: 'icon_detail_select_medium@2x.png',
    small: 'icon_detail_select_small@2x.png',
    baby: 'icon_detail_select_baby@2x.png',
    cat: 'icon_detail_select_cat@2x.png',
    pet: 'icon_detail_select_pet@2x.png',
    55067: 'icon_detail_select_bathe@2x.png',
    57302: 'icon_detail_select_pickup@2x.png',
}
var condImgMap = {
    balcony: 'icon_editor_balcony@2x.png',
    park: 'icon_editor_park@2x.png',
    seaside: 'icon_editor_seaside@2x.png',
    single: 'icon_editor_single@2x.png',
    suite: 'icon_editor_suite@2x.png',
    traffic: 'icon_editor_traffic@2x.png',
    villa: 'icon_editor_villa@2x.png'
}
var gradeStars = {
    empty: 'icon_detail_evaluate_empty@2x.png',
    half: 'icon_detail_evaluate_half@2x.png',
    all: 'icon_detail_evaluate_all@2x.png'
}
var imgSize = {
    face: '@!face',//头像 120*120
    tiny: '@!tiny',//240*240
    thumbnail: '@!thumbnail',//480*480
    small: '@!small',//小图 720*720
    big: '@!big',//大图 960*960
    original: '@'//原图
}
/**
 * 截取url后缀的对应参数值
 */
var getUrlParam = function(key){
    var params = location.href.split('?')[1];
    if(params){
        params = params.split('&');
        for(var i = 0; i < params.length ; i++){
            var param = params[i].split('=');
            if(param[0]==key){
                return param[1];
            }
        }
    }
}
/**
 * 日期格式化
 * @param date
 * @returns {string} '2010-11-06'
 */
var dateFomat = function(date){
    if(date!='' && date!=null){
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        month = month < 10? ('0'+month) : month;
        var date = date.getDate();
        date = date < 10? ('0'+date) : date;
        return year+'-'+month+'-'+date;
    }
    return date;
}
/**
 * 时间（long类型）格式化
 * @param time
 */
var timeFormat = function(time){

}
/**
 * 时间转换:2016-05-12->long类型
 * @param time
 */
var timeToLong = function(time){
    var times = time.split('-');
    var date = new Date();
    date.setFullYear(times[0]);
    date.setMonth(parseInt(times[1])-1);//月份从0开始
    date.setDate(times[2]);
    return date.getTime();
}
/**
 * 发表时间的转换
 * 2015-07-15 16:28:28 -> 7月15日 16:28,20分钟前
 * @param time
 * @returns {*}
 */
var timeSettled = function(dateTime){
    if(dateTime!='' && dateTime!=null){
        var now = new Date();
        //设置昨日凌晨时间
        var yDate = new Date();
        yDate.setDate(now.getDate()-1);
        yDate.setHours(0,0,0,0);
        var yesterday = yDate.getTime();//昨天0点毫秒数

        now = now.getTime();//当前时间毫秒数
        var publish = Date.parse(dateTime);//发表时间（yyyy-mm-dd h24:mi:as）毫秒数
        var space = now-publish ;//时间间隔毫秒数
        var h = 60*60*1000;//1 hour毫秒数
        if(space == h){
            return '1小时前';
        }else if(space < h){
            var spell = Math.round(space/1000/60);
            return spell+'分钟前';
        }else if(space < 24*h){
            var spell = Math.round(space/1000/60/60);
            return spell+'小时前';
        }else if(publish > yesterday){
            var t = dateTime.substring(11,16);
            return '昨天 '+t;
        }else{
            //转换成 7月15日 16:28
            var d = dateTime.substring(5,10),//mm-dd
                t = dateTime.substring(11,16);//h24:mi
            var dateStr = d.split('-').join('月')+'日 '+t;
            return dateStr;
        }
    }
    return dateTime;
}
/**
 * 计算经过的天数
 * @param startTime
 * @param endTime
 */
var getDemandDays = function(startTime,endTime){
    var start = timeToLong(startTime);
    var end = timeToLong(endTime);
    return Math.floor(Math.abs((end-start)/1000/3600/24));
}
/**
 * 加载中 开启动画
 */
var toolImgDir = 'img/';
var loadingTimer = null;
var order = 1;
var loadingAnimation = function(loadImgs){
    loadImgs.hide();
    switch (order++){
        case 1: $(loadImgs[0]).show();break;
        case 2: $(loadImgs[1]).show();break;
        case 3: $(loadImgs[2]).show();break;
        case 4: $(loadImgs[3]).show();break;
        case 5: $(loadImgs[4]).show();break;
    }
    order = order>5?1:order;
}
var loading = function(){
    var load = $('#loading'),loadImgs;
    if(load.length==0 || load==undefined || load==null){
        load = $('<div>').attr('id','loading');
        $('<img>').attr('src',toolImgDir+'load_animation_one@2x.png').appendTo(load);
        $('<img>').attr('src',toolImgDir+'load_animation_two@2x.png').appendTo(load);
        $('<img>').attr('src',toolImgDir+'load_animation_three@2x.png').appendTo(load);
        $('<img>').attr('src',toolImgDir+'load_animation_four@2x.png').appendTo(load);
        $('<img>').attr('src',toolImgDir+'load_animation_five@2x.png').appendTo(load);
        //覆盖整个页面的加载动画
        var pageWidth = getPageWidth();
        load.css({left: pageWidth/2-35}).appendTo($('body'));
    }
    loadImgs = load.children('img');
    load.show();
    loadingTimer = setInterval(function(){
        loadingAnimation(loadImgs);
    },100);
}
/**
 * 加载结束 关闭动画
 */
var loaded = function(){
    clearInterval(loadingTimer);
    $('#loading').fadeOut(200);
}
/**
 * emoji图片转换
 * @ 转换
 */
var emojiRoot = null;
var emojifyTo = function(nodes){
    var emoticons = [['@']];
    var emoImgDir = 'img/emoji/';
    /**
     * 匹配表情 替换成相应img
     * @param data
     * @param emot
     */
    var findingMarches = function(node,emoticon){
        var index = node.html().indexOf(emoticon[0]);
        if(index > -1){
            if(emoticon[0]=='@'){
                var str = node.html().match(/@\S*\s/g);
                if(str && str.length > 0){
                    for(var i = 0; i < str.length; i ++){
                        node.html(node.html().replace(str[i],"<label class='orange'>"+str[i]+"</label>"));
                    }
                }
            }else{
                //匹配到 替换
                node.html(node.html().replace(emoticon[0],"<img src='"+emoImgDir+emoticon[1]+".png' class='emoji' alt='"+emoticon[2]+"'>"));
                //继续遍历
                findingMarches(node,emoticon);
            }
        }
    }
    /**
     * 遍历表情
     * @param node
     */
    var matchAndInsertEmoji = function(node) {
        for(var i = 0; i < emoticons.length ; i++){
            var emoticon = emoticons[i];
            findingMarches(node,emoticon);
        }
    }
    if(emojiRoot==null){
        $.ajax({
            type: "GET",
            dataType: "xml",
            url: "emoji.xml",
            success: function(resText){
                emojiRoot = resText.documentElement;
                $(emojiRoot).children('emote').each(function(){
                    var cht = $(this).attr("cht");
                    var png = $(this).attr("png");
                    var chs = $(this).attr("chs");
                    var arr = [cht,png,chs];
                    emoticons.push(arr);
                });
                nodes.each(function(){
                    matchAndInsertEmoji($(this));
                })
            }
        });
    }else{
        $(emojiRoot).children('emote').each(function(){
            var cht = $(this).attr("cht");
            var png = $(this).attr("png");
            var chs = $(this).attr("chs");
            var arr = [cht,png,chs];
            emoticons.push(arr);
        });
        nodes.each(function(){
            matchAndInsertEmoji($(this));
        })
    }
}
/**
 * 获取地区编码
 * @param postcode 邮编
 * @param item 显示地址的元素
 */
var root = null;
var getRegionCode = function(){
    if(root==null){
        $.ajax({
            type: "GET",
            dataType: "xml",
            url: "region_code.xml",
            success: function(resText){
                root = resText.documentElement;
            }
        });
    }
}
var fillAddrInfo = function(postcode,item){
    var region = $(root).find("area[postcode='"+postcode+"']");//用户地区信息:省 市
    if(postcode && region.length>0){
        var city = '';
        if(region.length>0){
            city = region.parent().parent().attr('name')+' '+region.parent().attr('name');
        }else{
            region = $(root).find("city[postcode='"+postcode+"']");
            if(region.length>0){
                city = region.parent().attr('name')+' '+region.attr('name');
            }else{
                region = $(root).find("province[postcode='"+postcode+"']");
                city = region.attr('name');
            }
        }
        item.text(city);
    }else{
        item.text('可能来自火星');
    }
}
/**
 * 替换回车符成换行符
 * @param str
 */
var replaceStr = function(str){
    if(str!=null && str!=''){
        return str.replace(/\r\n/ig,'<br/>');
    }
    return str;
}
/**
 * 加密方法
 * @param value
 * @returns {*}
 */
var code = function(value){
    if(value=="" || value==null){
        return "";
    }
    $.base64.utf8encode = true;
    if(value instanceof Object){
        value.jsonData = JSON.stringify(value.jsonData);
        value = JSON.stringify(value);
    }
    value = $.base64.encode(value+"");
    var middle = value.substring(1,3).split("").reverse().join("");
    var arr0 = value.charAt(0);
    var arr1 = value.substring(3,value.length);
    return $.base64.encode(arr0.concat(middle.concat(arr1)));
}
/**
 * JSON数据的参数分别加密
 * @param data
 * @returns {{}}
 */
var paramCoding = function(data){
    var codedData = {};
    $.each(data,function(key,value){
        if(key=="?"){
            //不需加密的参数 图片等
            codedData[key] = value;
        }else{
            codedData[key] = code(value);
        }
    });
    return codedData;
}
/**
 * 提示框
 * @param message
 */
var showMessageAlert = function(message,delay){
    var messageAlertDiv = $("#messageAlert");
    if(messageAlertDiv.length==0 || messageAlertDiv==undefined || messageAlertDiv==null){
        messageAlertDiv = $("<div>").attr("id","messageAlert")
            .addClass("message_alert");
        $("<p>").text(message)
            .css({width: (message.length+2)+"em"})
            .appendTo(messageAlertDiv);
        $("body").append(messageAlertDiv);
    }else{
        messageAlertDiv.find("p").text(message)
            .css({width: (message.length+2)+"em"});
        messageAlertDiv.show();
    }
    if(delay){
        setTimeout(function(){
            messageAlertDiv.hide();
        },2000);
    }else{
        setTimeout(function(){
            messageAlertDiv.hide();
        },1000);
    }
}
/**
 * 下载APP
 */
$('#downloadApp').on('click',function(){
    window.open('http://a.app.qq.com/o/simple.jsp?pkgname=com.viptail.xiaogouzaijia','_self');
})
/**
 * 获取屏幕宽度
 * @returns {Number}
 */
function getPageWidth(){
    var pageWidth = window.innerWidth;
    if(typeof pageWidth != "number"){
        pageWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body.clientWidth;
    }
    return pageWidth;
}
/**
 * 获取屏幕宽度
 * @returns {Number}
 */
function getPageHeight(){
    var pageHeight = window.innerHeight;
    if(typeof pageHeight != "number"){
        pageHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body.clientHeight;
    }
    return pageHeight;
}
/**
 * 是否为微信
 * @returns {boolean}
 */
function isWechat() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}
/**
 * 判断设备类型:PC\移动
 */
function ifMobile(){
    var browser={
        versions:function(){
            var u = navigator.userAgent, app = navigator.appVersion;
            return {//移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
            };
        }(),
        language:(navigator.browserLanguage || navigator.language).toLowerCase()
    }
    if(browser.versions.mobile || browser.versions.ios || browser.versions.android ||
        browser.versions.iPhone || browser.versions.iPad){
        return true;
    }
    return false;
}
/**
 * 本地存储(若不支持HTML本地存储 则用cookie)
 * @param data
 */
var setLocalStorage = function(key,value){
    if(value instanceof Object){
        value = JSON.stringify(value);
    }
    if (window.localStorage) {
        localStorage.setItem(key, value);
    } else {
        Cookie.write(key, value);
    }
}
var getLocalStorage = function(key){
    return window.localStorage ? localStorage.getItem(key): Cookie.read(key);
}
var delLocalStorage = function(key){
    if (window.localStorage) {
        localStorage.removeItem(key);
    }
}
/**
 * 设置页面title 第一张图片
 */
var setShareInfo = function(title,img){
    document.title = title;
    document.getElementById('first').src = img;
}

